import React, { useEffect, useState } from "react";
import "./index.less";
import type { TableColumnsType, UploadProps } from "antd";
import { Badge, Button, InputNumber, Modal, Space, Table, message } from "antd";
import {
  getRoom,
  addRoom,
  deleteRoom,
  getRoomSites,
  lockSite,
} from "../../server/api";
import RoomForm from "../../components/RoomForm";
import { useForm } from "antd/es/form/Form";
import { COMURL } from "../../constant";
import { debug } from "console";

interface ExpandedDataType {
  id: number;
  siteNumber: number;
  siteStatus: number;
}

interface DataType {
  id: React.Key;
  roomName: string;
  openTime: string;
  closeTime: string;
  roomIntroduce: string;
  roomSize: number;
  roomRestSite: number;
}

const RoomManagement: React.FC = ({}) => {
  // const expandDataSource = Array.from({ length: 1 }).map<ExpandedDataType>(
  //   (_, i) => ({
  //     id: Math.random(),
  //     siteStatus: 0,
  //     siteNumber: 10,
  //   })
  // );

  const columns: TableColumnsType<DataType> = [
    {
      title: "房间图片",
      dataIndex: "roomPhoto",
      key: "roomPhoto",
      width: "80px",
      render: (roomPhoto: string) => (
        <div>
          <img src={`${COMURL}${roomPhoto}`} alt="room" width={"100%"} />
        </div>
      ),
    },

    { title: "名称", dataIndex: "roomName", key: "roomName" },
    {
      title: "描述",
      dataIndex: "roomIntroduce",
      key: "roomIntroduce",
      width: "20%",
      render: (value: string) => {
        return <div className="roomintroduce-text">{value}</div>;
      },
    },
    { title: "房间限制", dataIndex: "roomSize", key: "roomSize" },
    { title: "座位限制", dataIndex: "roomRestSite", key: "roomRestSite" },
    { title: "开放时间", dataIndex: "openTime", key: "openTime" },
    { title: "关闭时间", dataIndex: "closeTime", key: "closeTime" },
    {
      title: "操作",
      dataIndex: "operation",
      key: "operation",
      render: (_: any, record: any) => (
        <Space>
          <Button
            color="primary"
            variant="filled"
            onClick={() => editorRoom(record.id)}
          >
            编辑
          </Button>
          <Button
            color="danger"
            variant="filled"
            onClick={() => deleteRoomFunc(record.id)}
          >
            删除
          </Button>
          {/* <Button color="cyan" variant="filled" onClick={addRoom}>
            添加座位
          </Button> */}
        </Space>
      ),
    },
  ];

  const expandedRowRender = () => (
    <Table<ExpandedDataType>
      columns={expandColumns}
      dataSource={expandDataSource}
      pagination={false}
    />
  );
  const expandColumns: TableColumnsType<ExpandedDataType> = [
    { title: "座位编号", dataIndex: "siteNumber", key: "siteNumber" },
    {
      title: "座位状态",
      dataIndex: "siteStatus",
      key: "siteStatus",
      render: (siteStatus: number) => {
        return siteStatus === 0 ? (
          <Badge status="success" text="启用" />
        ) : (
          <Badge status="error" text="占用" />
        );
      },
    },
    {
      title: "操作",
      key: "operation",
      render: (_: any, record: any) => (
        <Space size="middle">
          <a onClick={() => handleLockSite(record.id)}>锁定座位</a>
        </Space>
      ),
    },
  ];
  const [roomData, setRoomData] = useState<DataType[]>([]);
  const [isOpenLockSite, setIsOpenLockSite] = useState(false);
  const [lockSiteTime, setLockSiteTime] = useState(0);
  const [roomId, setRoomId] = useState(0);
  const [roomOpen, setRoomOpen] = useState(false);
  const [form] = useForm();
  const [imageUrl, setImageUrl] = useState("");
  const [rangeDate, setRangeDate] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [expandDataSource, setExpandDataSource] = useState([]);
  const [siteId, setSiteId] = useState(0);
  const handleLockSite = (id: number) => {
    setSiteId(id);
    setIsOpenLockSite(true);
  };
  const [pgn, setPgn] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const handleLockSiteCancel = () => {
    setSiteId(0);
    setIsOpenLockSite(false);
  };
  const handleLockSiteOk = async () => {
    await lockSite({ lockTime: lockSiteTime, siteId });
    message.success("锁定成功");
    setSiteId(0);
  };
  const lockSiteTimeChanged = (e: any) => {
    setLockSiteTime(e);
  };

  const getRoomdata = async () => {
    const res: any = await getRoom({
      pageNum: pgn.current,
      pageSize: pgn.pageSize,
    });
    setRoomData(res.records);
  };

  const getSiteData = async (roomId: number) => {
    const res: any = await getRoomSites({ roomId });
    setExpandDataSource(res);
  };
  //添加房间
  const addRoomFunc = async () => {
    setRoomOpen(true);
  };
  //编辑房间
  const editorRoom = (id: number) => {
    setRoomOpen(true);
    setRoomId(id);
  };
  //删除房间
  const deleteRoomFunc = async (id: number) => {
    await deleteRoom({ roomId: id });
    message.success("删除成功");
    getRoomdata();
  };
  //提交表单
  const onFinish = async (values: any) => {
    console.log(values);
    if (roomId) {
      await addRoom({
        ...values,
        roomId,
        openTime: rangeDate[0],
        closeTime: rangeDate[1],
        roomPhoto: imageUrl,
      });
      message.success("编辑成功");
    } else {
      await addRoom({
        ...values,
        openTime: rangeDate[0],
        closeTime: rangeDate[1],
        roomPhoto: imageUrl,
      });
      message.success("添加成功");
    }
    form.resetFields();
    getRoomdata();
    setRoomId(0);
    setRoomOpen(false);
    setImageUrl("");
  };
  //获取开放关闭时间
  const dateChange = (date: any, dateString: any) => {
    setRangeDate(dateString);
  };

  const handleChange: UploadProps["onChange"] = (info) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      console.log(info);
      setLoading(false);
      //   setImageUrl(url);
    }
    if (!imageUrl) {
      info.file.status = "removed";
      setLoading(false);
    }
  };
  const onExpand = (expanded: boolean, record: any) => {
    getSiteData(record.id);
  };
  useEffect(() => {
    getRoomdata();
  }, []);
  return (
    <>
      <Modal
        open={roomOpen}
        onCancel={() => {
          form.resetFields();
          setRoomId(0);
          setRangeDate([]);
          setRoomOpen(false);
          setImageUrl("");
        }}
        footer={null}
        title={roomId ? "编辑房间" : "添加房间"}
      >
        <RoomForm
          form={form}
          onFinish={onFinish}
          dateChange={dateChange}
          imageUrl={imageUrl}
          setImageUrl={setImageUrl}
          loading={loading}
          setLoading={setLoading}
          handleChange={handleChange}
        ></RoomForm>
      </Modal>
      <Modal
        open={isOpenLockSite}
        onCancel={handleLockSiteCancel}
        onOk={handleLockSiteOk}
        okText="锁定座位"
        cancelText="取消"
        title="请输入时长"
      >
        <InputNumber
          addonAfter={"分"}
          defaultValue={0}
          value={lockSiteTime}
          onChange={(e) => lockSiteTimeChanged(e)}
        />
      </Modal>
      <div className="rmg-ctn">
        <Button onClick={addRoomFunc}>添加房间</Button>
        <Table<DataType>
          rowKey={(record) => record.id}
          columns={columns}
          expandable={{
            expandedRowRender,
            defaultExpandedRowKeys: ["0"],
            onExpand,
          }}
          dataSource={roomData}
          size="middle"
          className="room-management-table"
        />
      </div>
    </>
  );
};
export default RoomManagement;
